package redis

import (
	"context"
	"fmt"

	"gitee.com/chenhonghua/ginorigin/log"

	redis "github.com/go-redis/redis/v8"
)

type Redis struct {
	Host     string `mapstructure:"host" json:"host" yaml:"host"`
	Port     int    `mapstructure:"port" json:"port" yaml:"port"`
	Password string `mapstructure:"password" json:"password" yaml:"password"`
	DB       int    `mapstructure:"db" json:"db" yaml:"db"`
}

func (r Redis) Addr() string {
	return fmt.Sprintf("%s:%d", r.Host, r.Port)
}

func (r Redis) NewClient() (*redis.Client, error) {
	client := redis.NewClient(&redis.Options{
		Addr:     r.Addr(),
		Password: r.Password,
		DB:       r.DB,
	})
	if pong, e := client.Ping(context.Background()).Result(); e != nil {
		log.Errorf("redis连接失败[addr=%s]: %v", r.Addr(), e)
		return nil, e
	} else {
		log.Infof("redis连接成功: %s", pong)
	}
	return client, nil
}
